package com.jian.mall.ware.service.impl;

import com.jian.mall.common.content.PurchaseDetailStatusEnum;
import com.jian.mall.ware.entity.PurchaseEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jian.mall.common.utils.PageUtils;
import com.jian.mall.common.utils.Query;

import com.jian.mall.ware.dao.PurchaseDetailDao;
import com.jian.mall.ware.entity.PurchaseDetailEntity;
import com.jian.mall.ware.service.PurchaseDetailService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseDetailService")
public class PurchaseDetailServiceImpl extends ServiceImpl<PurchaseDetailDao, PurchaseDetailEntity> implements PurchaseDetailService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseDetailEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            wrapper.eq("id",key);
        }

        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)){
            wrapper.eq("status",status);
        }

        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }

        IPage<PurchaseDetailEntity> page = this.page(
                new Query<PurchaseDetailEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    @Override
    public void receivedPurchaseIds(List<PurchaseEntity> list) {
        List<Long> ids = list.stream().map(PurchaseEntity::getId).collect(Collectors.toList());

        List<PurchaseDetailEntity> entityList = purchaseDetailService.list(
                new QueryWrapper<PurchaseDetailEntity>().in("purchase_id", ids));

        List<PurchaseDetailEntity> collect = entityList.stream().peek(p -> p.setStatus(PurchaseDetailStatusEnum.STATUS_BUYING.getCode())).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);

    }

}